<template>
    <el-form label-width="100px">
      <el-form-item label="SPU 名称"> SPU 名称 </el-form-item>
      <el-form-item label="SKU 名称">
        <el-input placeholder="SKU 名称" v-model="skuInfo.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input type="number" v-model="skuInfo.price"></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)">
        <el-input type="number" v-model="skuInfo.weight"></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input type="textarea" placeholder="规格描述" rows="4" v-model="skuInfo.skuDesc"></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form label-width="100px" :inline="true">
          <el-form-item :label="attr.attrName" v-for="attr in attrList" :key="attr.id">
            <el-select placeholder="请选择" v-model="attr.attrIdValueId">
              <el-option :value="`${item.attrId}:${item.id}`" v-for="item in attr.attrValueList" :key="item.id" :label="item.valueName"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form label-width="100px" :inline="true">
          <el-form-item :label="attr.saleAttrName" v-for="attr in spuSaleAttrList" :key="attr.id">
            <el-select placeholder="请选择" v-model="attr.attrIdAttrValueId">
              <el-option :value="`${item.baseSaleAttrId}:${item.id}`" v-for="item in attr.spuSaleAttrValueList" :key="item.id" :label="item.saleAttrValueName"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
  
      <el-form-item label="图片列表">
        <el-table :data="spuImgList" border stripe @selection-change="selectChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="图片">
            <template v-slot="{row}">
              <img :src="row.imgUrl" alt="" width="100">
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-tag v-if="row.isDefault === '1'">默认图片</el-tag>
              <el-button type="primary" v-else @click="changeToDefault(row)">设为默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="default" @click="emit('setState', 0)">取消</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script lang="ts">
  import { defineComponent } from "vue";
  
  export default defineComponent({
    name: "SkuForm",
  });
  </script>
  
  <script setup lang="ts">
  import { requestSpuSaleAttrList,requestSpuImgList, type SpuInfoType, type SpuSaleAttrListType, type SpuImgListType, type SpuImgItemType } from "@/api/spu";
  import { storeToRefs } from "pinia";
  import useAttrStore from "@/stores/attr";
  import { requestAtrrInfo, type reqAttrReturnType } from "@/api/attr";
  import type { SkuInfoItemType } from "@/api/sku";
  import {onMounted, ref} from 'vue'
  import {requestSaveSkuInfo} from '@/api/sku'
  import { ElMessage } from "element-plus";
  
  //1.接受props传值
  const props = defineProps<{
    spuInfo: SpuInfoType;
  }>();
  const spuInfo = props.spuInfo;
  
  //2.接受自定义事件,用来切换组件
  const emit = defineEmits<{
    (event: "setState", state: number, row?: SpuInfoType): void;
  }>();
  
  //3.拿到pinia中的三级分类数据
  const attrStore = useAttrStore();
  const { category1Id, category2Id, category3Id } = storeToRefs(attrStore);

  //定义一个初始化的skuInfo到时候上传
  const skuInfo = ref<SkuInfoItemType>({
    //数据双向绑定的
    price: 0,
    skuName: '',
    skuDesc: '',
    weight: '',
    //从spuInfo获取的
    spuId: 0,
    tmId: 0,
    category3Id: 0,
    //设置的
    skuDefaultImg: '',
    skuImageList: [],
    skuAttrValueList: [],
    skuSaleAttrValueList: []
  })
  
  /* //获取所有的平台属性
  requestAtrrInfo(1id,2id,3id)==>reqAttrReturnType
  //获取当前spu所有销售属性
  requestSpuSaleAttrList()===>SpuSaleAttrListType
  //根据当前的spuId获取所有图片列表
  requestSpuImgList(spuId)===>SpuImgListType */
  //初始化需要的数据
  //平台属性
  const attrList = ref<reqAttrReturnType>([])
  //当前spu销售属性
  const spuSaleAttrList = ref<SpuSaleAttrListType>([])
  //图片列表
  const spuImgList = ref<SpuImgListType>([])
  const getInitData = async () => {
    const promise1 = requestAtrrInfo(
      category1Id.value as number,
      category2Id.value as number,
      category3Id.value as number
    );
    const promise2 = requestSpuSaleAttrList(spuInfo.id as number);
    const promise3 = requestSpuImgList(spuInfo.id as number);
    const result = await Promise.all([promise1, promise2, promise3]);
    //赋值
    attrList.value = result[0]
    spuSaleAttrList.value = result[1]
    spuImgList.value = result[2]
  };
  //初始化请求
  onMounted(() => {
    getInitData()
  })

  interface imgType{
    id: number,
    imgName: string,
    imgUrl: string,
    spuId: number
  }
  //定义一个新的图片列表接收
  const newImgList = ref<SpuImgListType>([])
  //选中图片
  const selectChange = (val:imgType[]) => {
    newImgList.value = val
  }
  //点击默认
  const changeToDefault = (row:SpuImgItemType) => {
    spuImgList.value.forEach(item => {
      item.isDefault = '0'
    })
    row.isDefault = '1'
  }

  //点击保存
  const save = async () => {
    //整理数据，从spuInfo获取的
    skuInfo.value.spuId = props.spuInfo.id
    skuInfo.value.tmId = props.spuInfo.tmId as number
    skuInfo.value.category3Id = props.spuInfo.category3Id
    //图片列表
    newImgList.value.forEach(item => {
      const obj = {
        imgName: item.imgName,
        imgUrl: item.imgUrl,
        spuImgId: item.id ,
        isDefault: item.isDefault
      }
      if(item.isDefault === '1'){
        skuInfo.value.skuDefaultImg = item.imgUrl
      }
      skuInfo.value.skuImageList?.push(obj)
    })
    //平台属性列表
    attrList.value.forEach(item => {
        if(item.attrIdValueId){
          const obj = {
            attrId: +item.attrIdValueId.split(':')[0],
            valueId: +item.attrIdValueId.split(':')[1]
          }
          skuInfo.value.skuAttrValueList?.push(obj)
        }
    })
    //销售属性列表
    spuSaleAttrList.value.forEach(item => {
        if(item.attrIdAttrValueId){
          const obj = {
            saleAttrId: +item.attrIdAttrValueId.split(':')[0],
            saleAttrValueId: +item.attrIdAttrValueId.split(':')[1]
          }
          skuInfo.value.skuSaleAttrValueList?.push(obj)
        }
    })
    //发送请求
    try {
      await requestSaveSkuInfo(skuInfo.value);
      ElMessage.success("新增sku成功");
      emit("setState", 0);
    } catch (e) {
      ElMessage.error("新增sku失败");
    }
  }
  </script>
  